package acm.na1996.northcentral;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;


public class p2120 {

	static int Z, I, M, L;
	static Map<Integer, Integer> set;
	static int counter;

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		counter = 1;
		set = new HashMap<Integer, Integer>();
		while (scanner.hasNext()) {
			Z = scanner.nextInt();
			I = scanner.nextInt();
			M = scanner.nextInt();
			L = scanner.nextInt();
			if (Z == 0 && I == 0 && M == 0 && L == 0) {
				break;
			}
			else {
				set.clear();
				System.out.print("Case " + counter + ": ");
				int id = 1;
				int clen = -1;
				set.put(L, id);				
				while (true) {
					L = ((Z * L) + I) % M;
					if (set.containsKey(L)) {
						int tmp = set.get(L);
						clen = id - tmp + 1;
						break;
					}
					else {
						++id;
						set.put(L, id);						
					}
				}
				counter++;
				System.out.println(clen);
			}
		}
	}

}
